import React, { useCallback, useEffect, useMemo, useState } from 'react'
import request from '../../api/request'
import style from './index.module.css'
import { InfiniteScroll } from 'antd-mobile'
interface SocoItem {
    restorativesimage?: string;
    restorativesname?: string;
    restorativesdesc?: string;
    restorativesprice?: number;
    restorativesid?: number;
    sales?: number;
    restorativessales?: number;
    sellCount?: number;
    salesCount?: number;
}
function Index() {
    const [soco,setSoco] = useState<SocoItem[]>([])

    const [pageCode,setPageCode] = useState(1)
    const pageSize = 10
    const [hasMore, setHasMore] = useState(true)
    const [sortKey, setSortKey] = useState('') // '', 'price', 'sales'
    const [sortOrder, setSortOrder] = useState('asc') // 'asc' | 'desc'

    type ApiResponse = { code: number; data: SocoItem[] }
    const getSoco = useCallback(async () => {
        const res = await request.get('/api/restorative/list',{
            params:{
                pageCode,
                pageSize
            }
        }) as unknown as ApiResponse
        console.log('获取药品数据列表',res);
        if(res.code === 200){
            setSoco(prev => [...prev,...(res.data as SocoItem[])])
            setPageCode(pageCode+1)
        }
        if(res.data.length === 0){
          setHasMore(false)
      }
    },[pageCode, pageSize])

    useEffect(() => {
        getSoco()
        // 仅在首次加载时调用
        // eslint-disable-next-line react-hooks/exhaustive-deps
    },[])
    
    const displayList = useMemo(() => {
        const list = [...soco]
        if (sortKey === 'price') {
            list.sort((a: SocoItem, b: SocoItem) => {
                const ap = Number(a?.restorativesprice ?? 0)
                const bp = Number(b?.restorativesprice ?? 0)
                return sortOrder === 'asc' ? ap - bp : bp - ap
            })
        } else if (sortKey === 'sales') {
            list.sort((a: SocoItem, b: SocoItem) => {
                const asales = Number(
                    a?.sales ?? a?.restorativessales ?? a?.sellCount ?? a?.salesCount ?? 0
                )
                const bsales = Number(
                    b?.sales ?? b?.restorativessales ?? b?.sellCount ?? b?.salesCount ?? 0
                )
                return sortOrder === 'asc' ? asales - bsales : bsales - asales
            })
        }
        return list
    }, [soco, sortKey, sortOrder])

    const toggleSort = (key: string) => {
        if (sortKey !== key) {
            setSortKey(key)
            setSortOrder('asc')
        } else {
            setSortOrder(prev => (prev === 'asc' ? 'desc' : 'asc'))
        }
    }
  return (
    <div className={style.socoBox}>
        <div className={style.sortBar}>
          <div
            className={`${style.sortItem} ${sortKey === 'price' ? style.active : ''}`}
            onClick={() => toggleSort('price')}
          >
            价格
            <span className={style.arrows}>
              <i className={`${style.arrow} ${style.up} ${sortKey === 'price' && sortOrder === 'asc' ? style.on : ''}`}></i>
              <i className={`${style.arrow} ${style.down} ${sortKey === 'price' && sortOrder === 'desc' ? style.on : ''}`}></i>
            </span>
          </div>
          <div
            className={`${style.sortItem} ${sortKey === 'sales' ? style.active : ''}`}
            onClick={() => toggleSort('sales')}
          >
            销量
            <span className={style.arrows}>
              <i className={`${style.arrow} ${style.up} ${sortKey === 'sales' && sortOrder === 'asc' ? style.on : ''}`}></i>
              <i className={`${style.arrow} ${style.down} ${sortKey === 'sales' && sortOrder === 'desc' ? style.on : ''}`}></i>
            </span>
          </div>
        </div>



        {displayList.length > 0 && displayList.map((item, index) => (
            <div key={index} className={style.socoBox1}>
              <img src={item.restorativesimage} alt="" />

              <div className={style.right}>
                <div className={style.titleRow}>
                  <span className={style.otc}>OTC</span>
                  <span className={style.otcright}>{item.restorativesname}</span>
                </div>

                <p className={style.yinc}>{item.restorativesdesc}</p>

                <span className={style.prices}>￥{item.restorativesprice}</span>
              </div>
            </div>
          ))}
           <InfiniteScroll loadMore={getSoco} hasMore={hasMore} />
    </div>
  )
}

export default Index
